<template>
  <div class="app-container">
    <!-- 搜索--------------------------------- -->
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>{{ $t("common.filterSearch") }}</span>
        <el-button
          style="float: right"
          @click="fetchData()"
          type="primary"
          size="small"
        >
          {{ $t("common.search") }}
        </el-button>
      </div>
      <div style="margin-top: 25px">
        <el-form :inline="true" :model="list" size="small" label-width="140px">
          <el-form-item :label="$t('qalist.search.id')">
            <el-input
              style="width: 203px"
              v-model="searchObj.id"
              :placeholder="$t('qalist.search.plid')"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('qalist.search.name')">
            <el-input
              style="width: 230px margin-left"
              v-model="searchObj.question"
              :placeholder="$t('qalist.search.plname')"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!--  -->
    <!--导入按钮 -->
    <el-button type="primary" @click="importData">
      <i class="fa fa-plus" />{{ $t("common.import") }}
    </el-button>
    <el-button @click="exportData" type="primary" plain>{{
      $t("common.export")
    }}</el-button>
    <!--  -->
    <!-- <div align="right">

      <el-button type="success" @click="addQA" icon="el-icon-plus"
        >新增问题</el-button
      >
    </div> -->

    <!-- 批量删除 -->
    <div style="margin-top: 20px">
      <el-button type="danger" size="mini" @click="removeRows()">{{
        $t("common.bulkDelete")
      }}</el-button>
    </div>

    <el-table
      :data="list"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column :label="$t('qalist.table.id')" width="100">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('qalist.table.question')">
        <template slot-scope="scope">
          {{ scope.row.question }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('qalist.table.answer')">
        <template slot-scope="scope">
          {{ scope.row.answer }}
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('common.operate')"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="editQA(row)"
          >
            {{ $t("common.update") }}
          </el-button>
          <!-- <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="delQA(row)"
          >
            {{ $t('common.delete') }}
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="导入" :visible.sync="dialogImportVisible" width="480px">
      <el-form label-position="right" label-width="170px">
        <el-form-item label="文件">
          <el-upload
            :action="'http://42.194.159.131:8080/emergencyQA/batchAdd'"
            :headers="headers"
            :on-success="onUploadSuccess"
            :multiple="false"
            class="upload-demo"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传excel文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- ----------------------------------分页 -->
    <div class="block" style="float: right; margin-top: 20px">
      <!-- <span class="demonstration">显示总数</span> -->
      <el-pagination
        background
        @current-change="fetchData"
        :current-page.sync="page_num"
        :page-size="page_size"
        layout="total, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- ------------------------------------ -->
    <!-- ---------------------------------------对话框-->
    <el-dialog
      :title="QA.id ? '修改问答信息' : '添加问答信息'"
      :visible.sync="dialogFormVisible"
    >
      <el-form style="width: 80%" :model="QA" :rules="rules" ref="ruleForm">
        <el-form-item label="问题标题" label-width="100px">
          <el-input autocomplete="off" v-model="QA.question"></el-input>
        </el-form-item>
        <el-form-item label="回答" label-width="100px">
          <el-input autocomplete="off" v-model="QA.answer"></el-input>
        </el-form-item>
        <!-- <el-form-item label="提问时间" label-width="100px"  prop="createTime">
          <el-date-picker
            v-model="QA.createTime"
            type="datetime"
            placeholder="选择提问日期时间"
            value-format="timestamp"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="回复时间" label-width="100px"  prop="updateTime">
          <el-date-picker
            v-model="QA.updateTime"
            type="datetime"
            placeholder="选择提问日期时间"
            value-format="timestamp"
          >
          </el-date-picker>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addorupdateQA">确 定</el-button>
      </div>
    </el-dialog>
    <!-- --------------------------------------- -->
  </div>
</template>

<script>
import axios from "axios";
import healqa from "@/api/healthyQA";
import { getToken } from "@/utils/auth";
export default {
  data() {
    return {
      dialogImportVisible: false, //弹框
      multipleSelection: [], //批量选择中选择的记录列表
      // -------------------------------------------日历
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      list: [], //列表条件封装对象
      page_num: 1,
      page_size: 5, //每5个数据一页
      total: 1, //初始化
      searchObj: {}, //条件封装对象
      dialogFormVisible: false, //对话框（查看）
      QA: {},
      headers: {
        Authorization: getToken(),
      },
      rules: {
        questionTitle: [
          { required: true, message: "请输入问题标题", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "blur",
          },
        ],
        answer: [
          { required: true, message: "请回复内容", trigger: "blur" },
          {
            min: 2,
            max: 100,
            message: "长度在 2 到 100 个字符",
            trigger: "blur",
          },
        ],
        // createTime: [
        //   { type: 'date', required: true, message: '请选择提问日期、时间', trigger: 'blur' },
        // ],
        // updateTime: [
        //   { type: 'date', required: true, message: '请选择回复日期、时间', trigger: 'blur' },
        // ],
      },
    };
  },
  created() {
    this.token = localStorage.getItem("token");
    this.fetchData();
  },
  methods: {
    importData() {
      this.dialogImportVisible = true;
    },
    //上传成功调用
    onUploadSuccess() {
      this.dialogImportVisible = false;
      this.fetchData(1);
      this.$message({
        message: "导入数据成功!",
        type: "success",
      });
    },
    //导出数据字典
    exportData() {
      this.btnLoading = true;
      axios({
        method: "get",
        url: "/emergencyQA/exportData",
        headers: {
          Authorization: getToken(),
        },
        responseType: "blob",
      })
        .then((res) => {
          this.btnLoading = false;
          if (res.data.type) {
            // 文件下载
            const blob = new Blob([res.data], {
              type: "application/vnd.ms-excel",
            });
            let link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.setAttribute("download", "健康问答.xlsx");
            link.click();
            link = null;
            // this.$message.success('导出成功');
          } else {
            // 返回json
            this.$message.warning(res.data.msg);
          }
        })
        .catch((err) => {
          this.btnLoading = false;
          this.$message.error("下载失败");
        });
    },
    //获取选择复选框的id值
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    //批量删除
    removeRows() {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //遍历数组得到每个id值，设置到idList里面
          var idList = [];
          for (var i = 0; i < this.multipleSelection.length; i++) {
            var obj = this.multipleSelection[i];
            var ids = obj.id;
            idList.push(ids);
          }
          //调用接口
          healqa
            .batchRemoveQA(idList)
            .then((resp) => {
              //提示
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              //刷新页面数据
              this.fetchData(1);
            })
            .catch(() => {
              this.$message({
                type: "error",
                message: "删除失败!权限不足，请联系管理员进行升级",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //时间格式化函数，此处仅针对yyyy-MM-dd hh:mm:ss 的格式进行格式化
    dateFormat: function (time) {
      var date = new Date(time);
      var year = date.getFullYear();
      var month =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hours =
        date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      var minutes =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      var seconds =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      // 拼接
      return (
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds
      );
    },
    //添加问题
    addQA() {
      this.dialogFormVisible = true;
      //清除一下数组
      this.QA = {};
    },
    //修改问题
    editQA(row) {
      this.dialogFormVisible = true;
      this.QA = { ...row };
    },
    //页面列表页渲染，请求接口调用
    //页面列表页渲染，请求接口调用
    fetchData(page = 1) {
      this.page_num = page;
      var vm = this;
      healqa
        .getHealthyQAList(this.page_num, this.page_size, this.searchObj)
        //请求成功调用
        .then((res) => {
          vm.list = res.data.page.records;
          vm.total = res.data.page.total;
        })
        .catch((error) => {});
    },
    //添加或者修改确定按钮
    async addorupdateQA() {
      //获取from结点，验证字段
      this.$refs.ruleForm.validate(async (success) => {
        //如果全部字段符合条件
        if (success) {
          this.dialogFormVisible = false;
          let result = await healqa.reqEditQA(this.QA);
          if (result.errorCode == 0) {
            this.$message({
              type: "success",
              message: this.QA.id ? "修改问答成功" : "添加问答成功",
            });
          }
          this.fetchData(this.QA.id ? this.page_num : 1); // 更新商品列表
          console.log("aaaaaaaaaaaaaaaaa", resp.data);
        } else {
          return false;
        }
      });
    },
    delQA(row) {
      this.$confirm("此操作将永久删除该题目信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //调用接口
          healqa.delqa(row.questionId).then((resp) => {
            //提示
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //刷新页面数据
            this.fetchData(1);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
